package com.dmw.reggie.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dmw.reggie.common.CustomException;
import com.dmw.reggie.entity.Category;
import com.dmw.reggie.entity.Dish;
import com.dmw.reggie.entity.Setmeal;
import com.dmw.reggie.mapper.CategoryMapper;
import com.dmw.reggie.service.CategoryService;
import com.dmw.reggie.service.DishService;
import com.dmw.reggie.service.SetmealService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {

    @Resource
    private CategoryMapper categoryMapper;

    @Resource
    private DishService dishService;

    @Resource
    private SetmealService setmealService;


    /**
     * 根据 id 删除分类，删除之前需要判断是否关联
     * @param id
     * @return
     */
    @Override
    public void removeById(Long id) {
        // 查询当前分类是否关联了菜品，如果关联了，则抛出自定义异常
        LambdaQueryWrapper<Dish> dishQueryWrapper = new LambdaQueryWrapper<>();
        dishQueryWrapper.eq(Dish::getCategoryId, id);
        if(dishService.count(dishQueryWrapper) > 0){
            throw new CustomException("当前分类下关联了菜品，不能删除！");
        }

        // 查询当前分类是否关联了套餐，如果关联了，则抛出自定义异常
        LambdaQueryWrapper<Setmeal> setmealQueryWrapper = new LambdaQueryWrapper<>();
        setmealQueryWrapper.eq(Setmeal::getCategoryId, id);
        if(setmealService.count(setmealQueryWrapper) > 0) {
            throw new CustomException("当前分类下关联了套餐，不能删除！");
        }

        // 调用父类的方法
        super.removeById(id);
    }
}
